package com.swak.frame.shrio.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import com.swak.frame.logger.SwakLoggerFactory;

public abstract class ShrioCorsAdviceFilter extends AdviceFilter {
    protected Logger logger = SwakLoggerFactory.getLogger(this.getClass());

    @Autowired(required = false)
    private ShrioPreHandleFilter shrioPreHandleFilter;

    @Override
    protected boolean preHandle(ServletRequest srequest, ServletResponse sresponse)
        throws Exception {
        HttpServletRequest request = (HttpServletRequest) srequest;
        HttpServletResponse response = (HttpServletResponse) sresponse;
        // 不为空，并且true，返回true
        if (shrioPreHandleFilter != null && shrioPreHandleFilter.preHandle(srequest, sresponse)) {
            return true;
        }

        setCorsHeader(request, response);
        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            logger.warn("http OPTIONS req,path:{},resp:200", request.getRequestURI());
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        return doHandleFilter(srequest, sresponse);
    }

    /**
     * 为response设置header，实现跨域
     */
    public void setCorsHeader(HttpServletRequest request, HttpServletResponse response) {
        String origin = request.getHeader("origin");
        if (StringUtils.isBlank(origin)) {
            origin = "*";
        }
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
            " Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }


    public abstract boolean doHandleFilter(ServletRequest srequest, ServletResponse sresponse)
        throws Exception;
}
